﻿#include "mainwindow.h"

#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QMovie>
#include <QScrollArea>
#include <QTimer>

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent) {
    setupUi();
    readConfig();
}

MainWindow::~MainWindow() = default;

void MainWindow::setupUi() {
    auto* central = new QWidget(this);
    auto* rootLayout = new QVBoxLayout(central);

    // === 顶部工具栏（仅 Open 按钮）===
    auto* topToolBar = new QHBoxLayout();
    btnOpen = new QPushButton(QStringLiteral("打开"), this);
    topToolBar->addWidget(btnOpen);
    topToolBar->addStretch(); // 右对齐（可选）

    // === 图像显示区域 ===
    imageLabel = new QLabel(this);
    imageLabel->setAlignment(Qt::AlignCenter);
    imageLabel->setMinimumSize(320, 240);
    imageLabel->setStyleSheet("background-color:#202020;color:#cccccc");

    auto* scroll = new QScrollArea(this);
    scroll->setWidgetResizable(true);
    scroll->setWidget(imageLabel);

    // === 底部控制栏（其他按钮）===
    auto* bottomControlBar = new QHBoxLayout();
    btnRewind = new QPushButton(QStringLiteral("ToStart"), this);
    btnPrev = new QPushButton(QStringLiteral("上一帧"), this);
    btnNext = new QPushButton(QStringLiteral("下一帧"), this);
    btnSlower = new QPushButton(QStringLiteral("减速"), this);
    btnFaster = new QPushButton(QStringLiteral("加速"), this);
    btnPlayPause = new QPushButton(QStringLiteral("播放"), this);

    // 按原始顺序添加按钮
    bottomControlBar->addWidget(btnRewind);
    bottomControlBar->addWidget(btnPrev);
    bottomControlBar->addWidget(btnNext);
    bottomControlBar->addWidget(btnSlower);
    bottomControlBar->addWidget(btnFaster);
    bottomControlBar->addWidget(btnPlayPause);

    // === 组合布局 ===
    rootLayout->addLayout(topToolBar);      // 顶部工具栏
    rootLayout->addWidget(scroll, 1);       // 图像区域（可伸缩）
    rootLayout->addLayout(bottomControlBar); // 底部控制栏

    setCentralWidget(central);

    // 连接信号槽（保持原样）
    connect(btnOpen, &QPushButton::clicked, this, &MainWindow::onOpen);
    connect(btnRewind, &QPushButton::clicked, this, &MainWindow::onRewind);
    connect(btnPrev, &QPushButton::clicked, this, &MainWindow::onPrev);
    connect(btnNext, &QPushButton::clicked, this, &MainWindow::onNext);
    connect(btnSlower, &QPushButton::clicked, this, &MainWindow::onSlower);
    connect(btnFaster, &QPushButton::clicked, this, &MainWindow::onFaster);
    connect(btnPlayPause, &QPushButton::clicked, this, &MainWindow::onPlayPause);

    updateUiState();
}

void MainWindow::updateUiState() {
    const bool hasMovie = movie && movie->isValid();
    btnRewind->setEnabled(hasMovie);
    btnPrev->setEnabled(hasMovie);
    btnNext->setEnabled(hasMovie);
    btnSlower->setEnabled(hasMovie);
    btnFaster->setEnabled(hasMovie);
    btnPlayPause->setEnabled(hasMovie);
}

void MainWindow::onOpen() {
    const QString path = QFileDialog::getOpenFileName(
        this,
        QStringLiteral("打开 GIF"),
        m_defaltFilePath,   // 默认路径设为 m_defaltFilePath
        QStringLiteral("GIF 文件 (*.gif)")
    );
    if (path.isEmpty()) return;
	m_defaltFilePath = path.left(path.lastIndexOf('/'));
    writeConfig();

    auto* newMovie = new QMovie(path);
    if (!newMovie->isValid()) {
        delete newMovie;
        return;
    }

    if (movie) {
        movie->stop();
        movie->deleteLater();
    }
    movie = newMovie;
    imageLabel->setMovie(movie);

    connect(movie, &QMovie::frameChanged, this, &MainWindow::onFrameChanged);

    speedFactor = 1.0;
    movie->setSpeed(100); // 100 = 1x
    movie->start();
    btnPlayPause->setText(QStringLiteral("暂停"));
    updateUiState();
}

void MainWindow::onRewind() {
    if (!movie) return;
    movie->stop();
    movie->jumpToFrame(0);
    imageLabel->repaint();
}

void MainWindow::jumpToFrame(int frame) {
    if (!movie) return;
    // QMovie 支持 jumpToFrame，但注意某些 GIF 不支持随机访问，会回退为逐帧计算
    movie->stop();
    movie->jumpToFrame(frame);
    imageLabel->repaint();
}

void MainWindow::onPrev() {
    if (!movie) return;
    const int count = movie->frameCount();
    if (count <= 0) return;
    int cur = movie->currentFrameNumber();
    int prev = (cur - 1 + count) % count;
    jumpToFrame(prev);
}

void MainWindow::onNext() {
    if (!movie) return;
    const int count = movie->frameCount();
    if (count <= 0) return;
    int cur = movie->currentFrameNumber();
    int next = (cur + 1) % count;
    jumpToFrame(next);
}

void MainWindow::onPlayPause() {
    if (!movie) return;
    if (movie->state() == QMovie::Running) {
        movie->setPaused(true);
        btnPlayPause->setText(QStringLiteral("播放"));
    } else {
        movie->setPaused(false);
        movie->start();
        btnPlayPause->setText(QStringLiteral("暂停"));
    }
}

void MainWindow::onFaster() {
    if (!movie) return;
    speedFactor = qMin(8.0, speedFactor * 1.25);
    movie->setSpeed(static_cast<int>(speedFactor * 100));
}

void MainWindow::onSlower() {
    if (!movie) return;
    speedFactor = qMax(0.1, speedFactor * 0.8);
    movie->setSpeed(static_cast<int>(speedFactor * 100));
}

void MainWindow::onFrameChanged(int) {
    // 可在状态栏显示帧号
}

void MainWindow::readConfig() {
    QFile configFile(m_configPath);
    if (!configFile.exists()) {
        m_defaltFilePath = QCoreApplication::applicationDirPath(); // 设置默认路径
        writeConfig();
    }
    else {
        // 文件存在，读取内容
        if (configFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&configFile);
            QString content = in.readAll();
            configFile.close();
            // 解析内容获取路径
            int startPos = content.indexOf("DefaltFilePath:") + 15;
            if (startPos >= 15) {
                m_defaltFilePath = content.mid(startPos).trimmed();
            }
            else {
                m_defaltFilePath = QCoreApplication::applicationDirPath(); // 格式错误使用默认路径
            }
        }
        else {
            qDebug() << "无法读取配置文件:" << configFile.errorString();
            m_defaltFilePath = QCoreApplication::applicationDirPath(); // 读取失败使用默认路径
        }
    }
}

void MainWindow::writeConfig() {
    QFile configFile(m_configPath);
    if (configFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&configFile);
        out << "DefaltFilePath:" << m_defaltFilePath;
        configFile.close();
    }
    else {
        qDebug() << "无法创建配置文件:" << configFile.errorString();
        m_defaltFilePath = ""; // 失败时设为空
    }
    configFile.close();
}


